import React, {Component, PropTypes} from 'react'
import {
  Button,
  Col,
  Form,
  Icon,
  Input,
  message,
  Modal,
  Popconfirm,
  Table,
} from 'antd'
import {fetchPost} from '../../../utils/request'
import Style from "./Index.less";
import AppBusinessProduct from './AppBusinessProduct'

const FormItem = Form.Item;

class BusinessProduct extends React.Component {

  constructor(props) {
    super(props)
    this.state = {
      visible: false,
      businessProducts: [],
      page: {
        currentPage: 1,
        pageSize: 13,
        totalCount: 0
      },
      loading: false,
      indeterminate: true,
      checkAll: false,
      bucketTagDisabled: false,
    }

  }

  componentDidMount() {
    this.getProductListData();
  }

  componentWillReceiveProps(props) {

  }

  //查询导流产品列表
  getProductListData() {
    fetchPost('/product/business/list').then((res) => {
      if (res.code === 0) {
        if (res.data !== null) {
          this.setState({
            businessProducts: res.data.businessProducts,
          })
        }
      } else {
        message.error(res.msg)
      }
    })
  }

  setPagination() {
    let self = this
    return {
      total: this.state.page.totalCount,
      pageSize: this.state.page.pageSize,
      showSizeChanger: false,
      showQuickJumper: true,
      showTotal(total) {
        return `Total ${total} `
      },
      onChange(current) {
        self.nextPage(current)
      }
    }
  }

  handleOk = (e) => {
    let self = this;
    this.props.form.validateFields((error, values) => {
      console.log(error, values);
      if (!error) {
        let params = {
          id: values.id,
          name: values.name,
          desc: values.desc,
          icon: values.icon,
          buttonText: values.buttonText,
          jumpUrl : values.jumpUrl
        }
        fetchPost('/product/business/save', params).then((res) => {
          if (res.code === 0) {
            message.info(res.msg, 0.2, () => {
              this.setState({
                visible: false,
              }, () => {
                this.getProductListData(), this.appBusinessProduct.getData();
              })
            })
            this.props.form.resetFields()
          } else {
            message.error(res.msg)
          }
        })
      }
    })
  }

  handleCancel = (e) => {
    this.setState({
      visible: false,
    }, () => {

    })
    this.props.form.resetFields();
  }

  deleteProduct(record) {
    console.log(record);
    fetchPost(`/product/business/delete/` + record.id, {
      id: record.id,
    }).then(res => {
      if (res.code === 0) {
        message.success('delete success')
        this.getProductListData()
      } else {
        message.error(res.msg)
      }
    })
  }

  showModal = (e) => {
    this.setState({
      bucketTagDisabled: false,
      visible: true,
    });
  }

  edit = record => {
    this.setState({
      bucketTagDisabled: false
    })
    this.props.form.setFieldsValue({
      name: record.name,
      id: "" + record.id,
      icon: record.icon,
      jumpUrl: record.jumpUrl,
      desc: record.desc,
      buttonText: record.buttonText,
    })
    this.setState({
      visible: true
    });
  };

  getRowKey(record) {
    return record.id;
  }

  render() {
    const {getFieldDecorator} = this.props.form
    let self = this
    let columns = [{
      title: 'Name',
      dataIndex: 'name',
    },{
      title: 'Icon',
      dataIndex: 'icon',
    }, {
      title: 'Desc',
      dataIndex: 'desc',
    },{
      title: 'JumpUrl',
      dataIndex: 'jumpUrl',
    },{
      title: 'ButtonText',
      dataIndex: 'buttonText',
    }, {
      title: 'Edit',
      dataIndex: 'edit',
      render: (text, record) => {
        return (
          <div>
            <a onClick={() => {
              this.edit(record)
            }}
               href='javascript:;'>Edit</a>
          </div>
        );
      },
    }, {
      title: 'Operate',
      dataIndex: 'operate',
      render: (text, record) => {
        return (
            <div>
              <Popconfirm title='Confirm to Delete?'
                          onConfirm={() => {
                            this.deleteProduct(record)
                          }}
                          okText='Confirm' cancelText='Cancel'>
                <a className='operateBtn' href='javascript:;'>Delete</a>
              </Popconfirm>
            </div>
        )
      },
    }
    ]

    const formItemLayout = {
      labelCol: {
        xs: {span: 8},
        sm: {span: 8},
      },
      wrapperCol: {
        xs: {span: 16},
        sm: {span: 16},
      },
    };

    return (
      <div>
        <Modal
          title="Add Product"
          visible={this.state.visible}
          onOk={this.handleOk}
          onCancel={this.handleCancel}
          okText="Save"
        >

          <Form style={{width: '100%', margin: 'auto'}} horizontal>

            <FormItem {...formItemLayout} label="id" style={{display: "none"}}>
              {getFieldDecorator('id', {})(
                <Input placeholder="required"/>
              )}
            </FormItem>

            <FormItem {...formItemLayout} label="Name">
              {getFieldDecorator('name', {
                rules: [
                  {required: true, message: 'Name is necessary!'},
                ],
              })(
                <Input placeholder="required" />
              )}
            </FormItem>

            <FormItem {...formItemLayout} label="Icon">
              {getFieldDecorator('icon', {
                rules: [
                  {required: true, message: 'Icon is necessary!'},
                ],
              })(
                <Input placeholder="required" />
              )}
            </FormItem>

            <FormItem {...formItemLayout} label="Desc">
              {getFieldDecorator('desc', {
                rules: [
                  {required: true, message: 'Desc is necessary!'},
                ],
              })(
                <Input placeholder="required" />
              )}
            </FormItem>

            <FormItem {...formItemLayout} label="JumpUrl">
              {getFieldDecorator('jumpUrl', {
                rules: [
                  {required: true, message: 'JumpUrl is necessary!'},
                ],
              })(
                <Input placeholder="required" />
              )}
            </FormItem>

            <FormItem {...formItemLayout} label="ButtonText">
              {getFieldDecorator('buttonText', {
                rules: [
                  {required: true, message: 'ButtonText is necessary!'},
                ],
              })(
                <Input placeholder="required" />
              )}
            </FormItem>
          </Form>

        </Modal>

        <div className={Style.title}>
          <Icon className={Style.icon} type='tag-o'/>
          Product Manage
          <Button className='ml20' onClick={(e) => {
            this.showModal(e)
          }} type='primary'> New </Button>
        </div>

        <div>
          <Col span={24}>
            <Table
                   key={(record) => {
                     this.getRowKey(record)
                   }}
                   rowKey={(record) => {
                     this.getRowKey(record)
                   }}
                   bordered
                   dataSource={this.state.businessProducts}
                   columns={columns}
                   loading={self.state.loading}
                   size='small'
            />
          </Col>
        </div>
      </div>
    )
  }
}
BusinessProduct = Form.create()(BusinessProduct)
export default BusinessProduct
